#!/usr/bin/env node

const Koa = require('koa'),
      Router = require('koa-router'),
      koaBody = require('koa-body'),
      fs = require('fs'),
      path = require('path');
const router = new Router(),
      app = new Koa();
const html = fs.readFileSync('./upload.html');

app.use(koaBody({
  multipart: true,
  formidable: {
    //xFileSize:1000*1024*1024 
    keepExtensions:true,
  onFileBegin:(name,file)=>{
    const dir = path.join(__dirname,'ipload');
    if(!fs.existsSync(dir)){
      fs.mkdirSync(dir);
    }
    const filePath = path.join(dir,`${file.name}`);
    file.path = filePath;
  },
onError:(err)=>{
  console.err(err);
}
  }
}));

router.get('/',async (ctx) => {
    ctx.set('Content-Type', 'text/html');
    ctx.body = html;
})
router.post('/upload',async (ctx)=>{
    const file = ctx.request.files.file;
    //console.log(ctx.request);
    const fileReader = fs.createReadStream(file.path);
    ctx.set('Content-Type','text/json');
    ctx.body = fileReader;
    
    //console.log(filePath);
    
    });
app.use(router.routes());
app.listen(3000);


